package sink

import (
	"database/sql"
	"fmt"
	"gomuisc/models/mysql"
)


func(sink MysqlSink) GetSheetList(page int,pagesize int,keyword string)(result []map[string]string,err error ){
	rows,err := sink.database.Query("select id,song_sheet_id,sheet_name,track_count from m_song_sheet where sheet_name  like ? limit ?,?", "%" + keyword + "%",page*pagesize,pagesize)
	if err != nil {
		fmt.Println("exec failed, ", err)
		return
	}
	//读出查询出的列字段名
	cols, _ := rows.Columns()
	//values是每个列的值，这里获取到byte里
	values := make([][]byte, len(cols))
	//query.Scan的参数，因为每次查询出来的列是不定长的，用len(cols)定住当次查询的长度
	scans := make([]interface{}, len(cols))
	//让每一行数据都填充到[][]byte里面
	for i := range values {
		scans[i] = &values[i]
	}

	var results  []map[string]string
	i:= 0
	for rows.Next() {
		if err = rows.Scan(scans...); err != nil { //query.Scan查询出来的不定长值放到scans[i] = &values[i],也就是每行都放在values里
			fmt.Println(err)
			return
		}
		row := make(map[string]string) //每行数据

		for k, v := range values { //每行数据是放在values里面，现在把它挪到row里
			key := cols[k]
			row[key] = string(v)
		}
		results = append(results,row)
		i++
	}
	//rows.handleRows(&sql.Rows{})
	return results,nil
}
func (sink MysqlSink) InsertSheet(single mysql.SongSheet) (err error) {
	var song_sheet_id  int
	err = sink.database.QueryRow("select song_sheet_id from m_song_sheet where song_sheet_id = ? ",
		single.Song_sheet_id).Scan(&song_sheet_id)
	fmt.Println(err)
	if err == sql.ErrNoRows {
		_, err = sink.database.Exec("insert into m_song_sheet(song_sheet_id,sheet_name,create_name,track_count) values (?,?,?,?)",
			single.Song_sheet_id, single.Sheet_name,single.Create_name,single.TrackCount)
		if err != nil {
			return
		}
		//err = sink.InsertYunyinyueUser(comment.User)
		return
	}
	return nil
}